package com.spider.demo1create;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

public class ThreadDemo3 {
    public static void main(String[] args) {
        //目标：掌握多线程的创建方式三：实现Callable接口，方式三的优势：可以获取线程执行完毕后的结果。
        Callable<  String> c1 = new MyCallable(100);
        FutureTask<String> f1 = new FutureTask<>(c1);
        Thread t1 = new Thread(f1);
        t1.start();
        Callable<  String> c2 = new MyCallable(3);
        FutureTask<String> f2 = new FutureTask<>(c2);
        Thread t2= new Thread(f2);
        t2.start();
        //获取线程执行结果
        try {
            System.out.println(f1.get());
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        try {
            System.out.println(f2.get());
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

//1.定义一个实现类实现Callable接口
class MyCallable implements Callable<String> {
    private int n;
    public MyCallable(int n) {
        this.n = n;
    }

    public MyCallable() {
    }

    @Override
    public String call() throws Exception {
        int sum = 0;
        for (int i = 0; i <= n; i++) {
                sum += i;
        }
        return "子线1-"+n+"的和"+sum ;
    }
}